package com.xxx.controller;

import com.xxx.common.AppResult;
import com.xxx.common.ResultCode;
import com.xxx.config.AppConfig;
import com.xxx.model.Article;
import com.xxx.model.ArticleReply;
import com.xxx.model.Board;
import com.xxx.model.User;
import com.xxx.services.IArticleService;
import com.xxx.services.IBoardService;
import com.xxx.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/article")
@Api(tags = "文章接口")
public class ArticleController {
    //从配置文件中读值, 如果找不到, 默认1
    @Value("${bit-forum.index.current-page:1}")
    private Integer currentPage;
    //从配置文件中读值, 如果找不到, 默认15
    @Value("${bit-forum.index.page-size:15}")
    private Integer pageSize;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IBoardService boardService;

    /**
     * 发布新帖
     *
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @PostMapping("/create")
    @ApiOperation("发布新帖")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //板块校验
        Board board = boardService.selectById(boardId);
        if (board == null || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        if (board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());

        //调用service
        articleService.create(article);

        return AppResult.success();
    }
//    @ApiOperation("获取帖子列表")
//    @GetMapping("/getAllByBoardId")
//    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId,
//                                                    @ApiParam("当前页数") @RequestParam(value = "currentPage")Integer currentPage){
//        List<Article> articles;
//        Integer offset = (currentPage - 1) * pageSize;
//        if(boardId == null){
//            articles = articleService.selectAll(offset, pageSize);
//        }else {
//            articles = articleService.selectAllByBoardId(boardId, offset, pageSize);
//        }
//        if(articles == null) articles = new ArrayList<>();
//        return AppResult.success(articles);

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articles;

        if (boardId == null) {
            articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        if (articles == null) articles = new ArrayList<>();
        return AppResult.success(articles);

    }

    @ApiOperation("获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        //从session中获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        Article article = articleService.selectDetailById(id);

        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断当前用户是否为作者
        if (Objects.equals(user.getId(), article.getUserId())) {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    /**
     * 修改帖子
     *
     * @param request
     * @param id
     * @param title
     * @param content
     * @return
     */
    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("文章id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {

        //从session中获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验帖子是否有效
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断用户是否是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }

        //判断帖子的状态
        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        articleService.modify(id, title, content);
        log.info("更新成功" + "id" + id + "title" + title + "content" + content);
        return AppResult.success();
    }

    /**
     * 点赞
     *
     * @param request
     * @param id
     * @return
     */
    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam("文章id") @RequestParam("id") @NonNull Long id) {
        //校验用户状态
        //从session中获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("文章id") @RequestParam("id") @NonNull Long id) {
        //校验用户状态
        //从session中获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验帖子是否有效
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断用户是否是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }

        //判断帖子的状态
        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        articleService.deleteById(id);
        return AppResult.success();
    }

    @ApiOperation("根据用户id查询帖子列表")
    @GetMapping("getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户id") @RequestParam(value = "userId", required = false) Long userId) {
        //如果userId为空, 则从session中获取用户信息
        if (userId == null) {
            //从session中获取当前登录用户
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);

    }

}
